<template>
  <div class="w-4/5 mx-auto mt-8">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon label-width="120px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="account">
        <el-input v-model="ruleForm.account" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="图形验证码" prop="code">
        <el-input v-model="ruleForm.code" />
        <div v-html="code" alt="" @click="getCaptchaImg" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">Submit</el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { getCaptcha, login } from "@/api/login/index"
import { reactive, ref } from "vue"
import type { FormInstance } from "element-plus"
import { useRouter } from "vue-router"
const ruleFormRef = ref<FormInstance>()
const code = ref()
const router = useRouter()
const ruleForm = reactive({
  account: "",
  password: "",
  code: ""
})

const submitForm = async () => {
  const data = await login(ruleForm)
  if (data.data) {
    window.localStorage.setItem("userInfo", JSON.stringify(data.data))
    router.push({ path: "/index" })
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const getCaptchaImg = async () => {
  const data = await getCaptcha()
  code.value = data
}
getCaptchaImg()
</script>
